﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using OracleDbTool;
using System.Windows.Forms.DataVisualization.Charting;

namespace hkjc
{
    public partial class FormTab : Form
    {
        string m_sql = string.Empty;
        string m_x_fieldname = "batchtime";
        List<string> m_line_fieldnames;
        string m_column_fieldname = string.Empty;
        DataSet m_dataset = null;
        public int m_index = 0;
        public double sortvalue = 0.0f;

        public FormTab(string caption,string sql,string column_fieldname, string line_fieldname1,
            string line_fieldname2,
            string line_fieldname3,
            string line_fieldname4,
            string line_fieldname5,            
            string x_fieldname = "batchtime",
            string line_fieldname6 = ""
           )
        {
            InitializeComponent();
            this.Text = caption;
            m_sql = sql;
            m_x_fieldname = x_fieldname;
            m_column_fieldname = column_fieldname;
            m_line_fieldnames = new List<string> { };
            if (!string.IsNullOrEmpty(line_fieldname1))
                m_line_fieldnames.Add(line_fieldname1);
            if (!string.IsNullOrEmpty(line_fieldname2))
                m_line_fieldnames.Add(line_fieldname2);
            if (!string.IsNullOrEmpty(line_fieldname3))
                m_line_fieldnames.Add(line_fieldname3);
            if (!string.IsNullOrEmpty(line_fieldname4))
                m_line_fieldnames.Add(line_fieldname4);
            if (!string.IsNullOrEmpty(line_fieldname5))
                m_line_fieldnames.Add(line_fieldname5);
            if (!string.IsNullOrEmpty(line_fieldname6))
                m_line_fieldnames.Add(line_fieldname6);

            chart1.MouseWheel += new MouseEventHandler(chart1_MouseWheel);
            chart1.MouseClick += new MouseEventHandler(chart1_MouseClick);
        }

        void chart1_MouseClick(object sender, MouseEventArgs e)
        {
            chart1.Focus();
        }

        void chart1_MouseWheel(object sender, MouseEventArgs e)
        {
            int delta = (e.Delta/120) * 5;
            if (Math.Abs(delta) < 1)
                delta = Math.Sign(delta);
            double maximum = chart1.ChartAreas[0].AxisY.Maximum + delta*1.0;
            chart1.ChartAreas[0].AxisY.Maximum = (maximum > 5.0 ? maximum : 5.0);
        }

        private void FormTab_Load(object sender, EventArgs e)
        {
            panel2.Dock = DockStyle.None;
            panel2.Visible = false;
            panel3.Dock = DockStyle.Fill;
            panel3.Visible = true;
            m_dataset = OrclFunc.QueryBySqlLocal(m_sql);
            dgvOddsTable.DataSource = m_dataset.Tables[0];

            int max_delta = 20;

            if (m_dataset.Tables[0].Rows.Count == 0)
                return;

            //label
            string timestr = m_dataset.Tables[0].Rows[0]["batchtime"].ToString();
            lblTabTitle.Text =  timestr.Substring(timestr.IndexOf(" ")+1) + "  " + m_line_fieldnames[0] + "=" + m_dataset.Tables[0].Rows[0][m_line_fieldnames[0]].ToString();

            //20150404
            

            sortvalue = Convert.ToDouble(m_dataset.Tables[0].Rows[0][m_line_fieldnames[0]]);

            //contextmenu
            for (int i = 0; i < m_line_fieldnames.Count; i++)
            {
                ToolStripMenuItem1.DropDownItems.Add(m_line_fieldnames[i], null, OnAddLineSeries);
                ToolStripMenuItemDel.DropDownItems.Add(m_line_fieldnames[i], null, OnDelLineSeries);
            }

            AddLineSeries(m_line_fieldnames[0]);

            string uppername = m_line_fieldnames[0].ToUpper();
            if (uppername == "DBL")
            {
                chart1.ChartAreas[0].AxisY.Maximum = 200 + max_delta;
                lblTabTitle.Text = lblTabTitle.Text + "  D_Y=" + float.Parse(m_dataset.Tables[0].Rows[0]["dbl_y"].ToString()).ToString("N5");
            }
            else if (uppername == "WIN")
            {
                chart1.ChartAreas[0].AxisY.Maximum = 30 + max_delta/2;
                lblTabTitle.Text = lblTabTitle.Text + "  W_Y=" + float.Parse(m_dataset.Tables[0].Rows[0]["win_y"].ToString()).ToString("N5");
            }
            else if (uppername == "PLA")
            {
                chart1.ChartAreas[0].AxisY.Maximum = 20 + max_delta/2;
                lblTabTitle.Text = lblTabTitle.Text + "  P_Y=" + float.Parse(m_dataset.Tables[0].Rows[0]["pla_Y"].ToString()).ToString("N5");
            }
            else if (uppername == "QIN")
            {
                chart1.ChartAreas[0].AxisY.Maximum = 200 + max_delta;
                lblTabTitle.Text = lblTabTitle.Text + "  Q_Y=" + float.Parse(m_dataset.Tables[0].Rows[0]["qin_Y"].ToString()).ToString("N5");
            }
            else if (uppername == "QPL")
            {
                chart1.ChartAreas[0].AxisY.Maximum = 100 + max_delta;
                lblTabTitle.Text = lblTabTitle.Text + "  QP_Y=" + float.Parse(m_dataset.Tables[0].Rows[0]["qpl_y"].ToString()).ToString("N5");
            }
            else if (uppername == "WIN%" || uppername == "PLA%" || uppername == "QIN%"
                || uppername == "QPL%" || uppername == "DBL_2%" || uppername == "DBL_1%")
            {
                chart1.ChartAreas[0].AxisY.Maximum = 50 + max_delta;
                /*Legend lg = new Legend();
                lg.DockedToChartArea = "ChartArea1";
                lg.Docking = Docking.Top;
                lg.Alignment = StringAlignment.Center;
                lg.IsDockedInsideChartArea = true;
                chart1.Legends.Add(lg);*/
            }
            else
                chart1.ChartAreas[0].AxisY.Maximum = 200 + max_delta;

            if (m_line_fieldnames[0] == "Dbl")
            {
                AddLineSeries("Win#");
                AddLineSeries("Dbl*");
                //added at 20150404
                AddLineSeries("Win*1");
                AddLineSeries("Win*2");
                AddLineSeries("Win*3");                
            }
            else if (m_line_fieldnames[0] == "Pla")
            {
                AddLineSeries("Win");
                AddLineSeries("Pla*");
                AddLineSeries("Pla#");
            }
            else if (m_line_fieldnames[0] == "Win")
            {
                //AddLineSeries("Pla");
                AddLineSeries("Win*");
                AddLineSeries("Win*+");
            }
            else if (m_line_fieldnames[0].ToUpper() == "QIN")
            {
                AddLineSeries("Qin*");
                AddLineSeries("Qin#");
                AddLineSeries("Qin*+");
                AddLineSeries("Qin#+");
            }
            else if (m_line_fieldnames[0].ToUpper() == "QPL")
            {
                AddLineSeries("Qpl*");
                AddLineSeries("Qpl#+");
                AddLineSeries("Qpl*+");
                AddLineSeries("Qpl#");
            }
            else if (m_line_fieldnames[0].ToUpper() == "WIN%")
            {
                AddLineSeries("PLA%");
                AddLineSeries("QIN%");
                AddLineSeries("QPL%");
                AddLineSeries("DBL_2%");
                AddLineSeries("DBL_1%");
            }
            if (!string.IsNullOrEmpty(m_column_fieldname))
                AddColumnSeries();
        }
        private void AddColumnSeries()
        {
            Series sr = new Series(m_column_fieldname);
            sr.ChartType = SeriesChartType.Column;
            sr.ChartArea = "ChartArea2";
            DataView dv = m_dataset.Tables[0].DefaultView;
            sr.Points.DataBindXY(dv, m_x_fieldname, dv, m_column_fieldname);
            chart1.Series.Add(sr);
        }

        private void OnAddLineSeries(object Sender,EventArgs e)
        {
            ToolStripMenuItem item = Sender as ToolStripMenuItem;

            bool bExists = false;
            foreach (Series sr in chart1.Series)
                if (sr.Name == item.Text)
                    bExists = true;
            if (!bExists)
                AddLineSeries(item.Text);
        }

        private void OnDelLineSeries(object Sender, EventArgs e)
        {
            ToolStripMenuItem item = Sender as ToolStripMenuItem;
            
            foreach (Series sr in chart1.Series)
                if (sr.Name == item.Text)
                {
                    chart1.Series.Remove(sr);
                    break;
                }                
        }

        private void AddLineSeries(string y_member)
        {
            Series sr = new Series(y_member);
            
            sr.ChartType = SeriesChartType.Line;
            sr.ChartArea = "ChartArea1";            
            //sr.Color = Color.DarkBlue;
            DataView dv = m_dataset.Tables[0].DefaultView;
            sr.Points.DataBindXY(dv, m_x_fieldname, dv, y_member);

            chart1.Series.Add(sr);
        }

        private void button1_Click(object sender, EventArgs e)
        {
            if (panel2.Visible)
            {
                panel2.Dock = DockStyle.None;
                panel2.Visible = false;
                //panel3.BringToFront();
                panel3.Dock = DockStyle.Fill;
                
                panel3.Visible = true;
            }
            else
            {
                panel3.Dock = DockStyle.None;
                panel3.Visible = false;
                //panel2.BringToFront();
                panel2.Dock = DockStyle.Fill;
                panel2.Visible = true;
                
            }
        }

        private void 显示Y增量图ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(m_column_fieldname))
                return;

            if (chart1.ChartAreas[1].Visible)
            {
                chart1.ChartAreas[1].Visible = false;
                chart1.ChartAreas[0].Position.Height = 95;
            }
            else
            {
                chart1.ChartAreas[0].Position.Height = 65;
                chart1.ChartAreas[1].Visible = true;
            }
            
        }

        private void button2_Click(object sender, EventArgs e)
        {
            m_dataset = OrclFunc.QueryBySqlLocal(m_sql);
            chart1.Series.Clear();
            AddColumnSeries();
            AddLineSeries(m_line_fieldnames[0]);
        }

        private void dgvOddsTable_DataBindingComplete(object sender, DataGridViewBindingCompleteEventArgs e)
        {
            foreach (DataGridViewColumn dgvc in dgvOddsTable.Columns)
            {
                dgvc.AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
            }
            dgvOddsTable.Columns[0].DefaultCellStyle.Format = "HH:mm:ss";
        }

        private void button3_Click(object sender, EventArgs e)
        {
            if (m_dataset == null)
                return;
            if (m_dataset.Tables[0].Rows.Count == 0)
                return;
            SaveFileDialog sfd = new SaveFileDialog();
            sfd.DefaultExt = "*.xlsx";
            sfd.Filter = "EXCEL(*.xlsx)|*.xlsx";
            sfd.Title = "EXCEL文件名";
            sfd.OverwritePrompt = true;
            if (sfd.ShowDialog() == System.Windows.Forms.DialogResult.OK && m_dataset.Tables[0].Rows.Count > 0)
                WebFunctions.ExportToExcel(dgvOddsTable, sfd.FileName, true);
        }

        private void dgvOddsTable_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
        {
            DataGridView dgv = sender as DataGridView;
            if (dgv.Columns.Count == 0)
                return;

            string fn = "";
            try
            {
                fn = dgv.Columns[e.ColumnIndex].Name.ToUpper();
            }
            catch (Exception)
            {
            }
            if (fn.Contains("HORSENO")
                || fn == "WIN"
                || fn == "PLA"
                || fn == "QIN"
                || fn == "QPL"
                || fn == "DBL"
                || fn == "WIN1"
                || fn == "WIN2"
                //|| fn == "PLA1"
                //|| fn == "PLA2"
                )
            {
                e.CellStyle.Font = new Font(dgv.Font, FontStyle.Bold);
                e.CellStyle.ForeColor = Color.Red;
                e.CellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;
            }
            //if ((fn.ToUpper() != "JOCKEY") && (fn.Contains("Y")
            //    || fn.Contains("INV")))
            else if ((fn.ToUpper() != "JOCKEY") && (fn.ToUpper() != "HORSENAME") && (fn.ToUpper() != "TRAINER") && (fn.ToUpper() != "BATCHTIME"))
            {
                e.CellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;
                e.CellStyle.Format = "N2";
            }

            float f = 0.0f;
            try
            {
                if (float.TryParse(e.Value.ToString(), out f))
                    if (f < 0)
                    {
                        e.CellStyle.BackColor = Color.LightBlue;
                    }
            }
            catch (Exception)
            {
            }
        }

        private void FormTab_SizeChanged(object sender, EventArgs e)
        {
            if (this.WindowState == FormWindowState.Maximized)
            {
                //显示图例
                /*if (chart1.Legends.Count == 0)
                {
                    Legend lg = new Legend();
                    lg.DockedToChartArea = "ChartArea1";
                    lg.Docking = Docking.Top;
                    lg.Alignment = StringAlignment.Center;
                    lg.IsDockedInsideChartArea = true;
                    chart1.Legends.Add(lg);
                }*/
            }
        }
    }
}
